package com.aiYouPms.admin.controller;

import com.aiYouPms.common.api.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Controller
@ResponseBody
@RequestMapping("/tools")
public class ToolsController {

    // 从配置文件中读取文件上传路径
    @Value("${file.upload.path:/tmp/uploads}")
    private String uploadPath;

    /**
     * 单文件上传
     *
     * @param file 上传的文件
     * @return 上传结果
     */
    @PostMapping("/upload")
    public HttpResult<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return HttpResult.error("上传文件不能为空");
        }

        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return HttpResult.error("文件名不能为空");
            }

            // 创建上传目录（如果不存在）
            Path uploadDir = Paths.get(uploadPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 生成唯一文件名，防止文件名冲突
            String fileExtension = "";
            if (originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

            // 构建文件保存路径
            Path filePath = uploadDir.resolve(uniqueFilename);

            // 保存文件
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 返回文件信息
            Map<String, Object> result = new HashMap<>();
            result.put("originalFileName", originalFilename);
            result.put("fileName", uniqueFilename);
            result.put("filePath", filePath.toString());
            result.put("fileSize", file.getSize());
            result.put("contentType", file.getContentType());

            log.info("文件上传成功: {} -> {}", originalFilename, uniqueFilename);
            return HttpResult.success("文件上传成功", result);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return HttpResult.error("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("文件上传异常", e);
            return HttpResult.error("文件上传异常: " + e.getMessage());
        }
    }

    /**
     * 多文件上传
     *
     * @param files 上传的文件数组
     * @return 上传结果
     */
    @PostMapping("/uploads")
    public HttpResult<Map<String, Object>> uploadFiles(@RequestParam("files") MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return HttpResult.error("请至少选择一个文件");
        }

        try {
            // 创建上传目录（如果不存在）
            Path uploadDir = Paths.get(uploadPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("totalFiles", files.length);
            result.put("uploadedFiles", new HashMap<String, Object>());

            int successCount = 0;
            int failCount = 0;

            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    failCount++;
                    continue;
                }

                try {
                    // 获取原始文件名
                    String originalFilename = file.getOriginalFilename();
                    if (originalFilename == null || originalFilename.isEmpty()) {
                        failCount++;
                        continue;
                    }

                    // 生成唯一文件名，防止文件名冲突
                    String fileExtension = "";
                    if (originalFilename.contains(".")) {
                        fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
                    }
                    String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

                    // 构建文件保存路径
                    Path filePath = uploadDir.resolve(uniqueFilename);

                    // 保存文件
                    Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

                    // 记录成功上传的文件信息
                    Map<String, Object> fileInfo = new HashMap<>();
                    fileInfo.put("originalFileName", originalFilename);
                    fileInfo.put("fileName", uniqueFilename);
                    fileInfo.put("filePath", filePath.toString());
                    fileInfo.put("fileSize", file.getSize());
                    fileInfo.put("contentType", file.getContentType());

                    ((Map<String, Object>) result.get("uploadedFiles")).put(uniqueFilename, fileInfo);
                    successCount++;
                } catch (Exception e) {
                    log.error("处理文件 {} 失败", file.getOriginalFilename(), e);
                    failCount++;
                }
            }

            result.put("successCount", successCount);
            result.put("failCount", failCount);

            if (successCount > 0) {
                log.info("批量文件上传完成: 成功 {} 个，失败 {} 个", successCount, failCount);
                return HttpResult.success("文件上传完成", result);
            } else {
                return HttpResult.error("所有文件上传失败");
            }
        } catch (Exception e) {
            log.error("批量文件上传异常", e);
            return HttpResult.error("批量文件上传异常: " + e.getMessage());
        }
    }
}
